<template>
    <div class="mapChart" ref="mapChart"></div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import { getMap } from '../../../api';

const mapChart = ref(null);

const map = (name, adcode) => {
    getMap(adcode).then(res => {
        const myChart = echarts.init(mapChart.value);
        echarts.registerMap(name, res.data);

        const option = {
            tooltip: {
                trigger: 'item',
                formatter: '{b}<br/>{c} (p / km2)',
            },
            geo: {
                map: name,
                label: {
                    emphasis: {
                        show: false,
                    },
                },
            },
            series: [
                {
                    type: 'effectScatter',
                    coordinateSystem: 'geo',
                    data: [
                        [116.405285, 39.904989],
                    ],
                },
                {
                    name: name,
                    type: 'map',
                    map: name,
                    label: {
                        show: true,
                        textStyle: {
                            color: '#fff',
                            fontSize: 10,
                        },
                    },
                    itemStyle: {
                        normal: {
                            areaColor: '#87CEEB',
                        },
                    },
                    data: res.data.features.map(item => ({
                        name: item.properties.name,
                        value: item.properties.childrenNum,
                        adcode: item.properties.adcode,
                    })),
                },
            ],
        };

        myChart.setOption(option);

        myChart.on('click', function (e) {
            const { name, adcode } = e.data;
            map(name, adcode);
        });
    }).catch(error => {
        console.error(error);
    });
};

onMounted(() => {
    map('中华人民共和国', 100000);
});
</script>

<style scoped>
.mapChart {
    width: 100%;
    height: 650px;
    margin-top: 100px;
}
</style>
